package com.example.demo.exception

import com.example.demo.exception.BaseException
import com.example.demo.utils.LogUtils
import com.example.demo.utils.MResult
import org.springframework.validation.BindException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.yaml.snakeyaml.constructor.DuplicateKeyException


@ControllerAdvice
@RestControllerAdvice
class BaseExceptionHandler {

    @ExceptionHandler(BaseException::class)
    fun handleRRException(e: BaseException): MResult<Nothing> {
        e.printStackTrace()
        return MResult<Nothing>().error(e.code, e.message.toString() ?: "服务器异常")
    }

    @ExceptionHandler(DuplicateKeyException::class)
    fun handleDuplicateKeyException(e: DuplicateKeyException): MResult<Nothing> {
        e.printStackTrace()
        LogUtils.e(e.message ?: "未知异常")
        return MResult<Nothing>().error(500, e.message.toString())
    }


    @ExceptionHandler(BindException::class)
    fun violationException(exception: BindException): MResult<Nothing> {
        LogUtils.e("BindException")
        val message = exception.allErrors[0].defaultMessage.toString()
        LogUtils.e(message ?: "未知异常")
        return MResult<Nothing>().error(400, message)
    }


    @ExceptionHandler(Exception::class)
    fun handleException(e: Exception): MResult<Nothing> {
        e.printStackTrace()
        LogUtils.e(e.message ?: "未知异常")
        return MResult<Nothing>().error(500, e.message.toString())
    }

}
